// stores/pointMallStore.js
import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'

export const usePointMallStore = defineStore('pointMall', () => {
	// 状态
	const myPoints = ref(0)
	const products = ref([])
	const isLoading = ref(false)
	const error = ref(null)

	// 统一请求方法
	const request = async (options) => {
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			})
		})
	}

	// 获取用户积分
	const fetchUserPoints = async (userId) => {
		try {
			isLoading.value = true
			const res = await request({
				url: `http://localhost:8080/api/pointmall/points?userId=${userId}`,
				method: 'GET'
			})
			myPoints.value = res.data.data
			error.value = null
		} catch (err) {
			error.value = err.message || '获取积分失败'
			myPoints.value = 0
		} finally {
			isLoading.value = false
		}
	}

	// 获取所有商品
	const fetchProducts = async () => {
		try {
			isLoading.value = true
			const res = await request({
				url: 'http://localhost:8080/api/pointmall/products',
				method: 'GET'
			})
			products.value = res.data.data || []
			error.value = null
		} catch (err) {
			error.value = err.message || '获取商品失败'
			products.value = []
		} finally {
			isLoading.value = false
		}
	}

	// 初始化数据
	const initData = async (userId) => {
		await Promise.all([
			fetchUserPoints(userId),
			fetchProducts()
		])
	}

	return {
		myPoints,
		products,
		isLoading,
		error,
		fetchUserPoints,
		fetchProducts,
		initData
	}
})